import Request from '@/utils/luch-request/index.js'
import store from '../store/index'
/**
 * @description: 封装请求
 * 2025-01-06
 * 以后请求方式全部改用导出方法的方式，不要再套用变量额外储存！如：export const colectNews ={...}
 正确例子：
 调取接口：
 export function getBusinessCat(params) {
   return request({
	 url: "index.php/api/BusinessManagerCat",
	 method: "GET",
	 data: params,
   });
 }
  页面调用
 import { getBusinessCat } from "@/api/business.js";
   getBusinessCat(params).then(res => {
	 console.log(res);
   })
 */

let http = new Request()
let isRefreshing = false; // 标志是否正在刷新token

//登录框显示弹框是否显示中(用于防止多次提示)
var loginTipShowing = false

/* config 为默认全局配置*/
http.setConfig((config) => {
	let env = '' //运行环境
	let baseUrl = '' // 接口地址
	if (process.env.NODE_ENV == 'development') {
		// 开发环境
		env = 'development'
		// baseUrl = 'http://8.138.214.11:8888/api'
		// baseUrl = 'https://www.yinyaoit.com/api'
		baseUrl = 'http://192.168.110.32:8888/api'
		// baseUrl = 'http://192.168.110.32:5003/api'

	} else {
		// 生产环境 (注：发行->打包上传小程序的方式才会来这里哦)
		env = 'production'
		// baseUrl = 'http://8.138.214.11:8888/api'
		baseUrl = 'https://www.yinyaoit.com/api'
		// 测试
		// baseUrl = 'http://192.168.110.15:8888/api'
	}

	store.commit('setEnv', env)
	store.commit('setBaseUrl', baseUrl)

	config.baseURL = baseUrl
	config.header = {
		...config.header
	}

	// config.header['X-Version-Code'] = uni.getSystemInfoSync().appVersionCode || ''

	// 默认有loading
	config.custom = {
		loading: true,
		title: '数据处理中...',
		mask: true
	}

	config.timeout = 60000 // 请求超时时间
	return config
})

/* 请求之前拦截器。可以使用async await 做异步操作 */
http.interceptors.request.use((config) => {
	config.header = {
		...config.header
	}

	// 配置token
	const token = uni.getStorageSync('token')
	// console.log('token', token)
	if (token) {
		config.header['Authorization'] = token
	}

	return config
}, (config) => {
	return Promise.reject(config)
})


/* 请求之后拦截器。可以使用async await 做异步操作  */
http.interceptors.response.use(async (res) => {
	if (res.config.custom.isNeedLoading) {
		uni.hideLoading()
	}
	return res
},
	async (response) => { // 请求错误做点什么。可以使用async await 做异步操作
		console.log(response, 'error');
		// console.log(isRefreshing, 'isRefreshing');

		if (response.config.custom.isNeedLoading) {
			uni.hideLoading()
		}
		// 请求响应错误
		var errorMsg = response.data ? response.data.detail ? response.data.detail : response.data.message : '网络不给力，请检查网络设置'

		if (!isRefreshing && response.statusCode == 401) {
			// console.log(8848);

			isRefreshing = true;
			let refreshData = await refreshToken(response.config); // 刷新 token
			// console.log(refreshData, "refreshData");
			return Promise.resolve(refreshData); // 返回新的 Promise
		}
		else if (response.statusCode == 401) {
		}
		else {
			isRefreshing = false;
			// uni.showToast({
			// 	title: errorMsg,
			// 	icon: 'none',
			// 	duration: 0
			// })
			// console.log(response, 'error', errorMsg);

			if (!response.config.custom.title) {
				setTimeout(() => {
					if (response.config.custom.title) {
						uni.showModal({
							title: '温馨提示',
							content: errorMsg || '',
							showCancel: false,
							confirmText: '知道了'
						})
					} else {

					}
				}, 100)
			}
			// console.log('####接口调用err', response);
			return Promise.reject({...response,errorMsg})
		}
	})

function request(params) {
	let {
		url,
		method,
		data,
		custom,
		header
	} = params

	method = method.toLowerCase()

	const requestParams = {
		url,
		method,
		custom,
		header
	}

	if (method == 'get') {
		if (custom && custom.unRemovesKeysWithNullValues) {
			Object.assign(requestParams, {
				params: data
			})
		} else {
			Object.assign(requestParams, {
				params: dealObjectValue(data)
			})
		}
	} else {
		if (custom && custom.unRemovesKeysWithNullValues) {
			Object.assign(requestParams, {
				data: data
			})
		} else {
			Object.assign(requestParams, {
				data: dealObjectValue(data)
			})
		}
	}
	return http.request(requestParams)
}

// 移除对象中存在空值的属性
const dealObjectValue = obj => {
	var param = {}

	if (obj === null || obj === undefined || obj === '') return param

	for (var key in obj) {
		if (obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
			param[key] = obj[key]
		}
	}
	return param
}
async function refreshToken(configs) {
	console.log(111);
	isRefreshing = true;
	let config = configs;
	let refresh_token = uni.getStorageSync('refresh_token');
	// console.log(refresh_token, "refresh_token");
	// console.log(config, "config");

	config.header.refresh_token = refresh_token;
	try {
		let res = await request(config);
		let data = res.data;
		// console.log(res, "data");
		console.log(res.header, "data.headers");
		// setAccessToken(data.headers.authorization);
		// setRefresh_token(data.headers.refresh_token);
		store.dispatch('setToken', res.header.authorization)
		store.dispatch('setRefresh_token', res.header.refresh_token)
		uni.setStorageSync('token', res.header.authorization)
		uni.setStorageSync('refresh_token', res.header.refresh_token)

		// console.log(res.header.authorization, "data.headers.authorization");
		isRefreshing = false;
		return res;
	} catch (error) {
		if (isRefreshing) {
			uni.showModal({
				title: '温馨提示',
				content: '当前页面已失效，请重新登录',
				showCancel: true,
				confirmText: '知道了',
				success: (res) => {
					if (res.confirm) {
						var pages = getCurrentPages()
						let currentRoute = pages[pages.length - 1].route;
						uni.redirectTo({ url: '/pages/user/login?redirect=/' + currentRoute });
						store.dispatch('setUserInfo', {})
						store.dispatch('setToken', '')
						store.dispatch('setRefresh_token', '')

						uni.removeStorageSync('userInfo');
						uni.removeStorageSync('token');
						uni.removeStorageSync('refresh_token');
						isRefreshing = false;
					} else if (res.cancel) {
						store.dispatch('setUserInfo', {})
						store.dispatch('setToken', '')
						store.dispatch('setRefresh_token', '')
						uni.removeStorageSync('userInfo');
						uni.removeStorageSync('token');
						uni.removeStorageSync('refresh_token');
						isRefreshing = false;
					}
				}
			})
		} else {
			store.dispatch('setUserInfo', {})
			store.dispatch('setToken', '')
			store.dispatch('setRefresh_token', '')

			uni.removeStorageSync('userInfo');
			uni.removeStorageSync('token');
			uni.removeStorageSync('refresh_token');
			isRefreshing = false;
		}


	}
};


export default request
